package com.wxb.qd.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxb.qd.common.ErrorCode;
import com.wxb.qd.common.PageResult;
import com.wxb.qd.dto.CurrentPage;
import com.wxb.qd.dto.CustomData;
import com.wxb.qd.dto.ExcelMessage;
import com.wxb.qd.entity.Aerodata;
import com.wxb.qd.entity.User;
import com.wxb.qd.exception.BusinessException;
import com.wxb.qd.mapper.AerodataMapper;
import com.wxb.qd.service.AerodataService;
import com.wxb.qd.service.UserService;
import com.wxb.qd.utils.MyMessageSender;
import com.wxb.qd.utils.TableListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
* @author 12796
* @description 针对表【aerodata】的数据库操作Service实现
* @createDate 2024-03-03 17:08:40
*/
@Service
@Slf4j
public class AerodataServiceImpl extends ServiceImpl<AerodataMapper, Aerodata>
    implements AerodataService{

    @Resource
    private TableListener tableListener;

    @Resource
    private UserService userService;

    @Resource
    private MyMessageSender myMessageSender;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 查找某个特定的数据
     * @param aerodata 气动类
     * @return 数据
     */
    @Override
    public Aerodata getAeroDataById(Aerodata aerodata) {
        if (aerodata == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",aerodata.getId());
        return this.getOne(queryWrapper);
    }

    /**
     * 查找某些特征数据
     * @param aerodata 含有特征的数据
     * @return 拥有这些特征的数据
     */
    @Override
    public List<Aerodata> getAeroDataBy(Aerodata aerodata) {
        if (aerodata == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>(aerodata);
        return this.list(queryWrapper);
    }

    /**
     * 分页查询
     * @param currentPage 页数和每页数量
     * @return 列表
     */
    @Override
    public PageResult<Aerodata> getAeroDataByPage(CurrentPage currentPage) {
        QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isDelete",0);
        Page<Aerodata> page = this.page(new Page<>(currentPage.getCurrent(), 10),queryWrapper);
        PageResult<Aerodata> pageResult=new PageResult<>();
        pageResult.setPageList(page.getRecords());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    /**
     * 分页查询可共享数据
     * @param currentPage 页数和每页数量
     * @return 列表
     */
    @Override
    public PageResult<Aerodata> getAeroDataByPageShare(CurrentPage currentPage) {
        //先去查缓存
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        String key = "wxb:qd:aerodata";
        Object o = operations.get(key);
        PageResult<Aerodata> pageResult=new PageResult<>();
        if(o == null){
            QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("isDelete",0);
            queryWrapper.eq("isShare",1);
            Page<Aerodata> page = this.page(new Page<>(currentPage.getCurrent(), 10),queryWrapper);
            operations.set(key,page);
            pageResult.setPageList(page.getRecords());
            pageResult.setTotal(page.getTotal());
            return pageResult;
        }
        ObjectMapper objectMapper =new ObjectMapper();
        Page page = objectMapper.convertValue(o, Page.class);
        pageResult.setPageList(page.getRecords());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    /**
     * 分页查询当前用户所有数据
     * @param currentPage 页数和每页数量
     * @return 列表
     */

    @Override
    public PageResult<Aerodata> getAeroDataByPageUser(CurrentPage currentPage, HttpServletRequest request) {
        QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>();
        User loginUser = userService.getLoginUser(request);
        queryWrapper.eq("isDelete",0);
        queryWrapper.eq("UserId",loginUser.getId());
        Page<Aerodata> page = this.page(new Page<>(currentPage.getCurrent(), 10),queryWrapper);
        PageResult<Aerodata> pageResult=new PageResult<>();
        pageResult.setPageList(page.getRecords());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    /**
     * 删除数据，将数据删除态设置为1
     * @param aerodata 数据
     * @return 删除成功
     */
    @Override
    public boolean deleteAeroData(Aerodata aerodata) {
        if (aerodata == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        aerodata.setIsDelete(1);
        //更新数据库中数据标记已删除的状态
        this.updateById(aerodata);
        //直接从缓存中删除掉
        return true;
    }


    /**
     * 读取excel文件是csv和xlsx都可以
     * @param file,id 文件
     * @return 读取成功
     */
    @Override
    public Boolean readExcel(MultipartFile file,String id) {
        String filename = file.getOriginalFilename();
        String property = System.getProperty("user.dir");
        String filePath = String.format("%s\\excelfile\\%s",property,filename) ;
        File destFile = new File(filePath);
        ExcelMessage excelMessage = new ExcelMessage();
        excelMessage.setFilePath(filePath);
        excelMessage.setId(id);
        if (destFile.exists()){
            if (!destFile.delete()) {
                // 如果删除失败，你可能想要抛出异常或返回错误
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件存在且删除失败");
            }
        }
        try{
            file.transferTo(new File(filePath));
            myMessageSender.sendExcelPath("myExchange","myRoutingKey",excelMessage);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新气动数据
     * @param aerodata 更新后的气动数据
     * @return 更新成功
     */
    @Override
    public boolean updateAeroData(Aerodata aerodata) {
        if (aerodata == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //更新jsonData
        aerodata.setJsonData("");
        String jsonString = JSON.toJSONString(aerodata);
        aerodata.setJsonData(jsonString);
        aerodata.setUpdateTime(new Date());
        //首先将数据更新
        return this.updateById(aerodata);
    }


    /**
     * 添加用户自定义数据，
     * @param customData 需要添加的自定义数据内容和该气动数据id
     * @return 更新是否成功
     */
    @Override
    public boolean addCustomData(CustomData customData) {
        //做个判空处理
        if (customData == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Aerodata> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Id",customData.getId());
        Aerodata aerodata = this.getOne(queryWrapper);
        //更新jsonData
        String jsonData = aerodata.getJsonData();
        JSONObject jsonObject = new JSONObject(jsonData);
        String customDataStr = JSONUtil.toJsonStr(customData.getCustomData());
        aerodata.setCustomData(customDataStr);
        JSONObject customJSON = new JSONObject(customDataStr);
        String data = customJSON.getStr("data");
        String dataIndex = customJSON.getStr("dataIndex");
        jsonObject.set(dataIndex,data);
        String jsonStr = jsonObject.toString();
        //保存
        aerodata.setJsonData(jsonStr);
        return this.updateById(aerodata);
    }

    /**
     * 添加json数据列
     * @param aerodata 需要转换为json的气动数据
     * @return 添加成功
     */
    @Override
    public boolean toJson(Aerodata aerodata) {
        if (aerodata.getJsonData()!=null){
            return false;
        }
        String jsonString = JSON.toJSONString(aerodata);
        aerodata.setJsonData(jsonString);
        //更新缓存
        return this.updateById(aerodata);
    }


    /**
     * 添加新气动数据
     * @param aerodata 气动数据
     * @return 新数据id
     */
    @Override
    public int addAeroData(Aerodata aerodata) {
        if (aerodata == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String jsonString = JSON.toJSONString(aerodata);
        aerodata.setJsonData(jsonString);
        aerodata.setCreateTime(new Date());
        aerodata.setIsShare(1);
        aerodata.setIsDelete(0);
        //数据库添加了
        this.save(aerodata);
        return aerodata.getId();
    }
}




